<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="1224" @ok="handleSubmit">
    <BasicForm @register="registerForm" ref="formRef">
      <template #productionSchedulingSchemeSlot="{ model, field }">
        <a-input-search :disabled="isDetail" v-model:value="model[field]" placeholder="请选择排产方案" readonly @search="openPsAlwaysScheduling" />
      </template>
    </BasicForm>
    <!-- 子表单区域 -->
    <a-tabs v-model:activeKey="activeKey" animated @change="handleChangeTabs">
      <a-tab-pane tab="主排产内容" key="psProductionArrangementPlansItem" :forceRender="true">
        <JVxeTable keep-source resizable ref="psProductionArrangementPlansItem"
          :rowNum="true" rowNumKey="rowNum"
          :loading="psProductionArrangementPlansItemTable.loading"
          :columns="psProductionArrangementPlansItemTable.columns"
          :dataSource="psProductionArrangementPlansItemTable.dataSource" :height="340" :rowNumber="true" :rowSelection="true" :toolbar="false" 
          @selectRowChange="handleSelectRowChange">
          <template #toolbarAfter>
            <a-button type="primary" @click="handleRelease" v-if="hasPermission('ps:ps_production_arrangement_plans:release')">释放订单</a-button>
          </template>
        </JVxeTable>
      </a-tab-pane>
    </a-tabs>
  </BasicModal>
  <!-- 方案选择 -->

  <psAlwaysSchedulingSelectModel @register="psAlwaysSchedulingRegModal" @getSelectResult="psAlwaysSchedulinghandleSuccess"
    v-bind="getBindValue"></psAlwaysSchedulingSelectModel>
</template>

<script lang="ts" setup>
import { ref, computed, unref, reactive } from 'vue';
import psAlwaysSchedulingSelectModel from '/@/views/components/psAlwaysSchedulingSelectModel.vue';
import { BasicModal, useModalInner, useModal } from '/@/components/Modal';
import { BasicForm, useForm } from '/@/components/Form/index';
import { JVxeTable } from '/@/components/jeecg/JVxeTable'
import { useJvxeMethod } from '/@/hooks/system/useJvxeMethods.ts'
import { formSchema, psProductionArrangementPlansItemColumns } from '../PsProductionArrangementPlans.data';
import { saveOrUpdate, psProductionArrangementPlansItemList } from '../PsProductionArrangementPlans.api';
import { VALIDATE_FAILED } from '/@/utils/common/vxeUtils';
import { usePermission } from '/@/hooks/web/usePermission';
import { useMessage } from '/@/hooks/web/useMessage';
const { hasPermission } = usePermission();
// Emits声明
const getBindValue = Object.assign({}, '');
const emit = defineEmits(['register', 'success']);
const isUpdate = ref(true);
const isDetail = ref<boolean>(false)
const formDisabled = ref(false);
const refKeys = ref(['psProductionArrangementPlansItem',]);
const activeKey = ref('psProductionArrangementPlansItem');
const psProductionArrangementPlansItem = ref();
const { notification } = useMessage();
const tableRefs = { psProductionArrangementPlansItem, };
const psProductionArrangementPlansItemTable = reactive({
  loading: false,
  dataSource: [],
  columns: psProductionArrangementPlansItemColumns
});
function psAlwaysSchedulinghandleSuccess(val) {
  setFieldsValue({
    productionSchedulingScheme: val[0].label,
    productionSchedulingSchemeId: val[0].value,
  });
}
// 主排产内容 选择的行数据的id
let planOrderItemSelectedRowIds = reactive([]);
//表单配置
const [registerForm, { setProps, resetFields, setFieldsValue, validate }] = useForm({
  labelWidth: 90,
  schemas: formSchema,
  showActionButtonGroup: false,
  baseColProps: { span: 8 }
});
//表单赋值
const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  //重置表单
  await reset();
  setModalProps({ confirmLoading: false, showCancelBtn: data?.showFooter, showOkBtn: data?.showFooter });
  isUpdate.value = !!data?.isUpdate;
  isDetail.value = !!data?.isDetail
  formDisabled.value = !data?.showFooter;
  if (unref(isUpdate)) {
    //表单赋值
    await setFieldsValue({
      ...data.record,
    });    
    requestSubTableData(psProductionArrangementPlansItemList, { id: data?.record?.id }, psProductionArrangementPlansItemTable)
  }
  // 隐藏底部时禁用整个表单
  setProps({ disabled: !data?.showFooter })
});
//方法配置
const [handleChangeTabs, handleSubmit, requestSubTableData, formRef] = useJvxeMethod(requestAddOrEdit, classifyIntoFormData, tableRefs, activeKey, refKeys);
const [psAlwaysSchedulingRegModal, { openModal: openpsAlwaysSchedulingModal }] = useModal();
//设置标题
const title = computed(() => (unref(isDetail) ? '详情' : !unref(isUpdate) ? '新增' : '编辑'));
function openPsAlwaysScheduling() {
  openpsAlwaysSchedulingModal(true, {
    isUpdate: false,
    showFooter: true,
    type: 1
  });
}
async function reset() {
  await resetFields();
  activeKey.value = 'psProductionArrangementPlansItem';
  psProductionArrangementPlansItemTable.dataSource = [];
}
function classifyIntoFormData(allValues) {
  let main = Object.assign({}, allValues.formValue)
  return {
    ...main, // 展开
    psProductionArrangementPlansItemList: allValues.tablesValue[0].tableData,
  }
}
 // 当选择的行变化时触发的事件
  function handleSelectRowChange(selectedRowIds) {
    planOrderItemSelectedRowIds = selectedRowIds.selectedRowIds;
  }
  //释放订单
  async function handleRelease() {
    if(planOrderItemSelectedRowIds.length > 0) {
      let ids = planOrderItemSelectedRowIds.toString();
      await releaseOrder({resultIds : ids});
      
      //关闭弹窗
      closeModal();
      //刷新列表
      emit('success');
    } else {
      notification.warning({
        message: "请先选择数据",
        duration: 3,
      });
    }
  }
//表单提交事件
async function requestAddOrEdit(values) {
  try {
    setModalProps({ confirmLoading: true });
    //提交表单
    await saveOrUpdate(values, isUpdate.value);
    //关闭弹窗
    closeModal();
    //刷新列表
    emit('success');
  } finally {
    setModalProps({ confirmLoading: false });
  }
}
function valueChange(e) {
  let index = e.columnIndex - 20
}
</script>

<style lang="less" scoped>
/** 时间和数字输入框样式 */
:deep(.ant-input-number) {
  width: 100%
}

:deep(.ant-calendar-picker) {
  width: 100%
}
</style>